/*
 * @Author: LIFM0623 1944099171@qq.com
 * @Date: 2024-01-11 17:28:46
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-05-15 16:47:21
 * @FilePath: \Scene_Back\src\auth\auth.controller.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
  Body,
  ClassSerializerInterceptor,
  Controller,
  Get,
  Inject,
  Post,
  Query,
  Req,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthGuard } from '@nestjs/passport';
import { LoginDto } from './dto/login.dto';
import { Public } from 'src/common/decorator/public.decorator';
import { Request } from 'express';
import { WINSTON_LOGGER_TOKEN } from 'src/winston/winston.module';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Inject(WINSTON_LOGGER_TOKEN)
  private logger;

  @Public()
  @UseGuards(AuthGuard('local'))
  @UseInterceptors(ClassSerializerInterceptor)
  @Post('login')
  async login(@Body() user: LoginDto, @Req() req) {
    this.logger.log(`用户[${user.email}]登陆系统`, `${AuthController.name}-${this.login.name}`);
    return await this.authService.login(user);
  }

  // @UseGuards(AuthGuard('jwt'))
  @Post('refreshToken')
  refreshToken(@Req() request: Request) {
    const authorizationHeader = (request.headers as any).authorization;
    let refresh_token: string | null = null;
    if (authorizationHeader) {
      // 通常，Authorization 头部的格式是 "Bearer token"
      const [bearer, value] = authorizationHeader.split(' ');
      if (bearer === 'Bearer' && value) {
        refresh_token = value;
      }
    }
    if (refresh_token) {
      return this.authService.refreshToken(refresh_token);
    }
  }
  @Public()
  @Get('checkToken')
  check_token(@Query('token') token: string) {
    return this.authService.checkToken(token);
  }
}
